package org.wk.affiliate.service;

import com.google.common.base.Strings;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.wk.affiliate.dao.NoticeDao;
import org.wk.affiliate.domain.NoticeManage;
import org.wk.affiliate.enums.NoticeStatus;
import org.wk.affiliate.view.NoticeVo;
import org.wk.core.common.view.PageVo;
import org.wk.core.common.view.ResponseVo;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author TangShenShen
 * @Description: 公告服务实现类
 * @date 2018/6/814:38
 */
@Service
public class NoticeServiceImpl implements NoticeService{
    @Autowired
    private NoticeDao noticeDao;

    @Autowired
    private HttpServletRequest request;

    @Override
    public ResponseVo findByPage(Integer page_num, Integer page_size) {
        int pageNo = page_num < 1 ? 0 : page_num - 1;
        int pageSize = page_size == null ? 10 : page_size;

        Page<NoticeManage> pages = noticeDao.findByNoticeStatusCode(NoticeStatus.PUBLISHED.getCode(),PageRequest.of(pageNo, pageSize, new Sort(Sort.Direction.DESC, "createTime")));




        Map<String,Object> resMap = new HashMap<>(2);
        List<Map<String,Object>> rows = new ArrayList<>();
        if (pages.getTotalElements()>0) {
            String url = request.getRequestURL().toString();
            for (NoticeManage entity:pages.getContent()) {
                Map<String,Object> temp = new HashMap<>();
                temp.put("id",entity.getId());
                temp.put("title",entity.getNoticeTitle());
                temp.put("releaseTime",new DateTime(entity.getCreateTime()).toString("MM月dd日 HH:mm"));
                temp.put("link",url+"/info/"+entity.getId());
                rows.add(temp);
            }
        }

        resMap.put("total",pages.getTotalElements());
        resMap.put("rows",rows);

        return ResponseVo.success().setData(resMap);
    }

    @Override
    public ResponseVo saveOrUpdate(NoticeVo noticeVo) {
        NoticeManage noticeManage;
        // id为空是  新增  不为空是更新
        if (Strings.isNullOrEmpty(noticeVo.getId())) {
            noticeManage = new NoticeManage();
            noticeManage.setNoticeStatusCode(NoticeStatus.UNPUBLISHED.getCode());
            noticeManage.setNoticeStatusName(NoticeStatus.UNPUBLISHED.getName());
        } else {
            noticeManage = noticeDao.getOne(noticeVo.getId());
        }
        // 赋值
        noticeManage.setNoticeTitle(noticeVo.getNoticeTitle());
        noticeManage.setNoticeContent((noticeVo.getNoticeContent().replace("<p>","")).replace("</p>",""));
        // 是否点击发布按钮
        if (noticeVo.isPushFlag()) {
            noticeManage.setNoticeStatusCode(NoticeStatus.PUBLISHED.getCode());
            noticeManage.setNoticeStatusName(NoticeStatus.PUBLISHED.getName());
        }
        noticeDao.saveOrUpdate(noticeManage);
        return ResponseVo.success();
    }

    @Override
    public PageVo queryPage(Map<String, Object> params) {
        String noticeTitle = (String)params.get("noticeTitle");
        String temp = (String)params.get("page");
        Integer pageNo = temp==null?0:Integer.parseInt(temp)-1;
        temp = (String) params.get("limit");
        Integer pageSize = temp==null?10:Integer.parseInt(temp);

        NoticeManage noticeManage = new NoticeManage();
        noticeManage.setNoticeTitle(noticeTitle);
//        noticeManage.setNoticeStatusCode(NoticeStatus.PUBLISHED.getCode());   是否已发布
        Page<NoticeManage> page = noticeDao.findAll(new Specification<NoticeManage>() {
            @Override
            public Predicate toPredicate(Root<NoticeManage> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(null!=noticeManage.getNoticeTitle()&&!"".equals(noticeManage.getNoticeTitle())){
                    list.add(criteriaBuilder.like(root.get("noticeTitle").as(String.class), "%"+noticeManage.getNoticeTitle()+"%"));
                }
                if(null!=noticeManage.getNoticeStatusCode()&&!"".equals(noticeManage.getNoticeStatusCode())){
                    list.add(criteriaBuilder.equal(root.get("noticeStatusCode").as(String.class), noticeManage.getNoticeStatusCode()));
                }
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        }, PageRequest.of(pageNo, pageSize, new Sort(Sort.Direction.DESC, "createTime")));

        SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        List<NoticeVo> noticeVos = new ArrayList<>();
        for(NoticeManage notice : page.getContent()){
            NoticeVo noticeVo = new NoticeVo();
            BeanUtils.copyProperties(notice,noticeVo);
            noticeVo.setCreateTime(sdf.format(notice.getCreateTime()));
            noticeVos.add(noticeVo);
        }
        PageVo<NoticeVo> pageVo = new PageVo<NoticeVo>();
        pageVo.setTotal(page.getTotalElements());
        pageVo.setPageNo(++pageNo);
        pageVo.setPageSize(pageSize);
        pageVo.setResult(noticeVos);
        pageVo.setTotalPages(page.getTotalPages());
        return pageVo;
    }

    @Override
    public ResponseVo selectById(String noticeId) {
        NoticeVo noticeVo = new NoticeVo();
        NoticeManage noticeManage = noticeDao.getOne(noticeId);
        BeanUtils.copyProperties(noticeManage, noticeVo);
        if (noticeVo.getNoticeStatusCode().equals(NoticeStatus.PUBLISHED.getCode())){
            return  ResponseVo.success("not_edit","已经发布的公告不能修改!");
        }
        noticeVo.setPushFlag(NoticeStatus.PUBLISHED.getCode().equals(noticeManage.getNoticeStatusCode()));
        return ResponseVo.success().setData(noticeVo);
    }

    @Override
    public NoticeManage selectByIdForApp(String noticeId) {
        Optional<NoticeManage> optional = noticeDao.findById(noticeId);
        return optional.get();
    }

    @Override
    public NoticeManage getNewNotice() {
        return noticeDao.getNewNotice();
    }
}
